package com.andaily.web.controller.mobile.user;

import com.andaily.domain.dto.user.UserFormDTO;
import com.andaily.infrastructure.support.LogHelper;
import com.andaily.service.UserService;
import com.andaily.web.controller.validator.UserFormValidator;
import com.andaily.web.util.CookieUserAssistant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * @author Shengzhao Li
 */
@Controller
@RequestMapping("/user/setting")
public class UserFormController {

    private static LogHelper log = LogHelper.create(UserFormController.class);

    @Autowired
    private UserService userService;
    @Autowired
    private UserFormValidator userFormValidator;

    /**
     * Load form action
     *
     * @param model Model
     * @return View path
     * @throws Exception Exception
     */
    @RequestMapping(method = RequestMethod.GET)
    public String setupForm(ModelMap model) throws Exception {
        log.debug("Load user setting form page");
        UserFormDTO userFormDTO = userService.loadUserFormDTO();
        model.addAttribute("userForm", userFormDTO);
        model.addAttribute("userCookieKey", CookieUserAssistant.USER_COOKIE_KEY);
        return "user/user_form";
    }

    /**
     * Submit the form action
     *
     * @param userForm UserFormDTO
     * @param result   BindingResult
     * @param model    ModelMap
     * @return Redirect path
     * @throws Exception Exception
     */
    @RequestMapping(method = RequestMethod.POST)
    public String submit(@ModelAttribute("userForm") UserFormDTO userForm,
                         BindingResult result, ModelMap model) throws Exception {
        userFormValidator.validate(userForm, result);
        if (result.hasErrors()) {
            return "user/user_form";
        }
        log.debug("Submit by " + userForm);
        boolean updateResult = userService.updateUserSetting(userForm);
        return "redirect:/m/user/setting?result=" + updateResult;
    }

}
